# 图片上传接口
import pathlib
import uuid

# 导入接口文档生成相关装饰器和类
from drf_spectacular.utils import extend_schema, extend_schema_view, inline_serializer
from rest_framework import viewsets, serializers, status, views
from rest_framework.decorators import action
from rest_framework.response import Response
# 导入自定义配置
from dj_interview_api_server.settings import EDITOR_UPLOAD_ROOT, EDITOR_UPLOAD_URL


# 富文本编辑器wangeditor图片上传接口
@extend_schema_view(
    wang_editor_upload=extend_schema(
        summary='wangeditor富文本编辑器图片上传',
        tags=['文件上传'],
        description='wangeditor富文本编辑器图片上传接口',
        request=inline_serializer(
            name="wangeditor_upload",
            fields={
                "image":serializers.FileField(),
            }
        )
    )
)
class EditorUploadViewSet(viewsets.ViewSet):
    # 图片上传接口
    @action(methods=['post'], detail=False)
    def wang_editor_upload(self,request):
        # 接收图片数据
        image=request.FILES.get('image')
        if not image:
            return Response(data={'detail':'参数错误, 请传递参数image'},status=status.HTTP_400_BAD_REQUEST)
        # 获取图片文件原始后缀
        suffix=pathlib.Path(image.name).suffix
        # 保存目录
        dir_path=EDITOR_UPLOAD_ROOT
        # 如果目录不存在
        if not dir_path.exists():
            # 创建目录
            dir_path.mkdir()
        # 随机生成图片文件名称
        image_name=uuid.uuid4().hex+suffix
        # 拼接图片保存路径地址
        full_path=EDITOR_UPLOAD_ROOT / image_name
        # 获取项目域名
        curr_domain=request.build_absolute_uri('/')
        with open(full_path,'wb') as f:
            for chunk in image.chunks():
                f.write(chunk)
        data={
            "errno": 0,
            "data": {
                "url":curr_domain+EDITOR_UPLOAD_URL+image_name,
            }
        }
        return Response(data=data)
